import { message, type TableColumnsType } from "ant-design-vue";
import { formatTime } from "@/utils/common";
import { composeRuleGenerateErrorLogsApi, exportGenerateErrorLogsApi } from "@/api/esArticle";
import { getUserGroupApi, getUsersApi } from "@/api";
import { useExportSearch, useUserOptions } from "./useCommon";
import { useCommonAsyncOptions } from "./useEsArticleCommon";
import commonAsyncOptionsStore from "@/stores/commonAsyncOptions";
import { computedAsync } from "@vueuse/core";
export function useTableColumn() {
    const columns: TableColumnsType = [
        {
            title: "规则名",
            dataIndex: "rule_name",
            key: "rule_name",
            align: "center",
            minWidth: 100
        },
        {
            title: "关键词",
            dataIndex: "keyword",
            key: "keyword",
            align: "center",
            minWidth: 250
        },
        {
            title: "错误信息",
            dataIndex: "message",
            key: "message",
            align: "center",
            width: 160
        },
        {
            title: "生成索引",
            dataIndex: "generate_index",
            key: "generate_index",
            align: "center",
            width: 120
        },
        {
            title: "网站组",
            dataIndex: "website_group_name",
            key: "website_group_name",
            align: "center",
            width: 120
        },
        {
            title: "规则负责人",
            dataIndex: "create_name",
            key: "create_name",
            align: "center",
            width: 100
        },
        {
            title: "操作用户所在组",
            dataIndex: "user_group_name",
            key: "user_group_name",
            align: "center",
            width: 150
        },
        {
            title: "操作用户",
            dataIndex: "user_name",
            key: "user_name",
            align: "center",
            width: 100
        },
        {
            title: "记录时间",
            dataIndex: "@timestamp",
            key: "@timestamp",
            align: "center",
            customRender: (row) => h("div", {}, { default: () => formatTime(row.value) }),
            sorter: true
        }
    ];
    const action: TableColumnsType[0] = {};
    return {
        columns: [...columns, action]
    };
}
export type Options = {
    userGroupOptions: SelectOption;
    userOptions: SelectOption;
    createOptions: SelectOption;
    websiteGroupOptions: SelectOption;
};
export type TableItem = ComposeErrorLogResponseDataItem & {
    create_name: string;
    user_name: string;
    user_group_name: string;
    websit_group_name: string;
};

export function useState<OP extends Ref<SelectOption>>(...ops: [OP, OP, OP, OP]) {
    const tableData = ref<Array<TableItem>>([]);
    const getParams = reactive({
        page: 1,
        size: 10,
        keyword: "",
        message: "",
        isHandle: "",
        createId: 0, //创建者id
        ruleName: "", //规则名
        generateIndex: "", //生成索引
        websiteGroupId: 0, //网站组id
        userGroupIds: [], //用户组列表 格式 1,2,3
        uid: 0,
        order: "desc",
        sort_field: ""
    });
    const searchBody = ref<Record<string, any>>({});
    const searchLoading = ref(false);
    const fieldObj: Record<string, string> = {
        userGroupIds: "user_group_ids",
        generateIndex: "generate_index",
        createId: "create_id",
        ruleName: "rule_name",
        isHandle: "is_handle",
        websiteGroupId: "website_group_id"
    };

    const total = ref(0);
    const spinStyle = computed(() => {
        return { minHeight: window.innerHeight - 260 + "px" };
    });
    const getData = () => {
        searchLoading.value = true;
        const obj: Partial<GetComposeErrorLogParams> = {};
        for (const key in getParams) {
            // @ts-ignore
            if (getParams[key]!!) {
                // 将属性名 更换为小驼峰
                if (key in fieldObj) {
                    if (key === "userGroupIds") {
                        // @ts-ignore
                        obj[fieldObj[key]] = getParams[key].join(",");
                    } else {
                        // @ts-ignore
                        obj[fieldObj[key]] = getParams[key];
                    }
                } else {
                    // @ts-ignore
                    obj[key] = getParams[key];
                }
            }
        }
        composeRuleGenerateErrorLogsApi(obj, "get")
            .then((res) => {
                if (res.data.code === 200) {
                    total.value = res.data.count;
                    searchBody.value = res.data.search_body;
                    handleData(res.data.data, ...ops).then((res) => {
                        tableData.value = res.value;
                    });
                } else {
                    message.error("加载失败!");
                }
            })
            .catch(() => {
                message.error("服务器错误");
            })
            .finally(() => {
                searchLoading.value = false;
            });
    };
    // 导出搜索结果
    const exportSearch = useExportSearch(searchBody, exportGenerateErrorLogsApi, "error_log");
    watch(() => getParams.page, getData);
    onMounted(getData);
    return {
        tableData,
        ...toRefs(getParams),
        total,
        spinStyle,
        searchLoading,
        searchFunc: getData,
        exportSearch
    };
}
const userOptions = useUserOptions()
// 获取Options
export function useGetOptions(): Record<keyof Options, Ref<SelectOption>> {
    const { websiteGroupOptions } = useCommonAsyncOptions("get", false);
    const $store = commonAsyncOptionsStore();
    $store.init("create_name");
    const createOptions = toRef($store.options, "create_name");
    const userOptions = ref<SelectOption>([]);
    const userGroupOptions = ref<SelectOption>([]);
    getUserGroupApi().then((res) => {
        if (res.data.code === 200) {
            userGroupOptions.value = res.data.data;
        }
    });
    return {
        userGroupOptions,
        userOptions,
        createOptions,
        websiteGroupOptions
    };
}
async function handleData<OP extends Ref<SelectOption>>(
    data: Array<ComposeErrorLogResponseDataItem>,
    userOptions: OP,
    userGroupOptions: OP,
    websiteGroupOptions: OP,
    createOptions: OP
): Promise<Ref<Array<TableItem>>> {
    return computedAsync(() => {
        const result = data.map((item1) => {
            let value = "";
            value = (
                createOptions.value.find((item2: SelectOptionItem) => item2.value === item1["create_id"]) || {
                    label: ""
                }
            ).label;
            Reflect.set(item1, "create_name", value);
            value = (
                websiteGroupOptions.value.find((item2: SelectOptionItem) => item2.value === item1["website_group_id"]) || {
                    label: ""
                }
            ).label;
            Reflect.set(item1, "website_group_name", value);

            value = (
                userOptions.value.find((item2: SelectOptionItem) => item2.value === item1["uid"]) || {
                    label: ""
                }
            ).label;
            Reflect.set(item1, "user_name", value);

            value = (
                userGroupOptions.value.find((item2: SelectOptionItem) => item2.value === item1["user_group_ids"]) || {
                    label: ""
                }
            ).label;
            Reflect.set(item1, "user_group_name", value);
            return item1;
        });
        return result;
    }) as Ref<Array<TableItem>>;
}
